import { MessageType } from "./common/structs";
import initBusFrame from "./bus-frame";

let requestFilter = (
  url: string,
  resourceType: string,
  req: chrome.devtools.network.Request
) => true;

initBusFrame(PUBLIC_URL + "panel.html", (iframe) => {
  chrome.devtools.network.onRequestFinished.addListener((req) => {
    const { request, response } = req;
    // @ts-ignore
    if (!requestFilter(request.url, req._resourceType, req)) {
      return;
    }
    // const urlObj = new URL(request.url);
    // if (
    //   /^(127|192|0)(\.\d+){3}$|localhost|\.clickpaas\.com$/.test(
    //     urlObj.hostname
    //   )
    // ) {
    //   if (/^\/api\//.test(urlObj.pathname)) {
    //     // chrome.extension.getBackgroundPage()!.postMessage({
    //     //   type: 'relay',
    //     //   args: [request.url, {
    //     //     method: request.method
    //     //   }]
    //     // }, '*')
    //   }
    // }

    req.getContent((content) => {
      iframe.contentWindow!.postMessage(
        {
          code: 100,
          data: {
            id: req._request_id,
            url: request.url,
            method: request.method,
            initiator: req._initiator,
            // @ts-ignore
            resourceType: req._resourceType,
            request: {
              headers: request.headers,
              body: request.postData,
            },
            response: {
              statusCode: response.status,
              body: content,
              headers: response.headers,
            },
            startedDateTime: req.startedDateTime,
            time: req.time,
            timings: req.timings,
          },
        },
        "*"
      );
    });
  });
  chrome.devtools.network.onNavigated.addListener((url) => {
    iframe.contentWindow!.postMessage(
      {
        code: MessageType.PageNavigated,
        data: url,
      },
      "*"
    );
  });
  chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (tabId !== chrome.devtools.inspectedWindow.tabId) {
      return;
    }
    iframe.contentWindow!.postMessage(
      {
        code: MessageType.TabUpdated,
        data: changeInfo,
      },
      "*"
    );
  });
  return {
    setRequestFilter(code: string) {
      requestFilter = new Function(`return (${code})`)();
    },
  };
});
